package com.zjw.study.thread04_sharedata;

/**
 * 进阶第一课，ThreadLocal的线程内变量共享
 * @author Administrator
 *
 */
public class SingleShareThreadLocal {
	//声明变量，并初始化
	private static int data = 0;
	
	private ThreadLocal<Integer> tl = new ThreadLocal<>();
	
	public static void main(String[] args) {
		SingleShareThreadLocal stu = new SingleShareThreadLocal();
		stu.share01();
	}
	
	/**
	 * 提出问题，第二次或第三次执行getA获取的可能是第一次的值
	 */
	void share01() {
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					data ++;
					System.out.println(Thread.currentThread().getName() + "：" + data);
					tl.set(data);
					new A().getA();
					new B().getB();
				}
			}).start();
		}
	}
	
	
	class A {
		void getA() {
			System.out.println("A " + Thread.currentThread().getName() + " data=" + tl.get());
		}
	}
	class B {
		void getB() {
			System.out.println("B " + Thread.currentThread().getName() + " data=" + tl.get());
		}
	}

}
